<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    @ok="onOkButtonClick"
    ok-text="派单"
  >
    <a-alert
      v-if="type == 2"
      message="批量派单将使用各单元的责任部门和责任人作为隐患治理的责任主体。"
      type="info"
      style="margin-bottom: 10px"
      show-icon
    />
    <BasicForm @register="registerForm"></BasicForm>
    <template #footer>
      <a-button @click="closeModal">取消</a-button>
      <a-popconfirm
        title="是否确定进行派单，派单后不能进行撤销操作。"
        ok-text="确认"
        cancel-text="取消"
        @confirm="onOkButtonClick"
      >
        <a-button type="primary">派单</a-button>
      </a-popconfirm>
    </template>
    <Loading :loading="loading" tip="派单中,请耐心等待" />
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, onMounted, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { troubleCorrectDispatchSchema } from './troubleCorrect.data';
  import { queryProjectUsersDetail } from '/@/api/project/user';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getUnitDivision } from '/@/api/ehs/unitDivision';
  import { getUserOrganization, getOrganization } from '/@/api/ehs/organization';
  import { getDeptUsers } from '/@/api/public/public';
  import { Loading } from '/@/components/Loading';
  import {
    dispatchEhsTroubleCorrect,
    batchDispatchEhsTroubleCorrect,
  } from '/@/api/ehs/troublecorrect';
  const { globalProjectCode } = useGlobSetting();
  import moment from 'moment';
  import { getOrgDeptTree } from '/@/api/ehs/organization';
  const { createMessage } = useMessage();
  export default defineComponent({
    components: { BasicModal, BasicForm, Loading },
    name: 'TroubleDispatchModal',
    emits: ['success'],
    setup(props, { emit }) {
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 100,
        schemas: troubleCorrectDispatchSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      const type = ref();
      const loading = ref(false);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref();
      const ids = ref();
      const deptData = ref();
      const orgcode = ref();
      const [register, { closeModal, changeLoading }] = useModalInner((data) => {
        resetFields();
        if (data != undefined && data != null) {
          dataId.value = null;
          ids.value = [];
          let unrefData = unref(data);
          let tmpids = null;
          let tmpdataId = null;
          qcUnifyProps.value = unrefData;
          if (unrefData?.ids && unrefData?.ids.length == 1 && !unrefData?.dataId) {
            tmpdataId = unrefData.ids[0];
            tmpids = null;
          } else if (unrefData?.dataId && !unrefData?.ids) {
            tmpdataId = unrefData.dataId;
            tmpids = null;
          } else if (unrefData?.ids && unrefData?.ids.length > 1 && !unrefData?.dataId) {
            tmpdataId = null;
            tmpids = unrefData.ids;
          }
          console.log(tmpdataId, tmpids, '232432423');
          //接收父组件传递的数据
          if (tmpdataId) {
            dataId.value = tmpdataId;
            getUnitDivision(data.unitid).then((res) => {
              setFieldsValue({
                deptid: res?.resdeptid > 0 ? res.resdeptid : null,
                userid: res?.resuserid > 0 ? res.resuserid : null,
                userphone: res?.resuserphone,
                title: data.title,
              });
              getOrgDeptTree(orgcode.value).then((res1) => {
                deptData.value = res1;
                updateSchema([
                  {
                    field: 'title',
                    ifShow: false,
                  },
                  {
                    field: 'deptid',
                    ifShow: true,
                    componentProps: {
                      onChange: (value) => {
                        setFieldsValue({
                          userid: '',
                        });
                      },
                      treeData: res1,
                      treeDefaultExpandAll: true, //默认展开
                      listHeight: 220,
                      getPopupContainer: (triggerNode) => document.body,
                      fieldNames: { label: 'title', value: 'key', children: 'children' },
                    },
                  },
                  {
                    field: 'userid',
                    ifShow: ({ values }) => data.type === 1 && values.deptid,
                  },
                  {
                    field: 'userphone',
                    ifShow: ({ values }) => data.type === 1 && values.deptid,
                  },
                  {
                    field: 'description',
                    ifShow: data.type === 1,
                  },
                ]);
              });
            });
          } else if (tmpids) {
            updateSchema([
              {
                field: 'title',
                ifShow: true,
              },
              {
                field: 'deptid',
                ifShow: false,
              },
              {
                field: 'endtm',
                componentProps: {
                  // onChange: (value) => {
                  //   console.log('value', value);
                  //   setFieldsValue({
                  //     title: `截至${moment(value).format('YYYY年MM月DD日')}共有${
                  //       tmpids.length
                  //     }条隐患待整改治理`,
                  //   });
                  // },
                },
              },
            ]);
            setFieldsValue({
              title: `截至${moment().format('YYYY年MM月DD日')}共有${tmpids.length}条隐患待整改治理`,
            });
            ids.value = tmpids;
          }
          type.value = data.type;
        }
      });
      async function onOkButtonClick() {
        const values = await validate();
        loading.value = true;
        console.log(type.value, 'type');
        if (type.value === 1) {
          getDeptUsers(values.deptid).then((res) => {
            dispatchEhsTroubleCorrect({
              id: dataId.value,
              endtm: values.endtm,
              deptid: values.deptid,
              deptname: treeToArray(deptData.value).find((item) => item.key == values.deptid)
                ?.title,
              userid: values.userid,
              username: res.find((item) => item.id == values.userid)?.name,
              userphone: values.userphone,
              description: values.description,
            })
              .then((res) => {
                if (!res) {
                  createMessage.success('派发成功');
                  loading.value = false;
                  closeModal();
                  emit('success');
                }
              })
              .catch((err) => {
                loading.value = false;
                console.log('派发失败');
              });
          });
        } else {
          batchDispatchEhsTroubleCorrect({
            ids: ids.value,
            endtm: values.endtm,
            title: values.title,
            description: values.description,
          })
            .then((res) => {
              if (!res) {
                createMessage.success('批量派发成功');
                loading.value = false;
                closeModal();
                emit('success');
              }
            })
            .catch((err) => {
              loading.value = false;
              console.log('派发失败');
            });
        }
      }

      // tree结构扁平化
      function treeToArray(treeNodes) {
        let result = [];

        //递归函数 traverse，用于处理单个节点
        function traverse(node, fatherId) {
          const newNode = { ...node };
          if (fatherId) {
            newNode.fatherId = fatherId;
          }
          delete newNode.children;
          // 将没有子节点的新节点添加到结果数组中
          result.push(newNode);

          // 如果当前节点包含 children 属性（即有子节点）
          if (node.children) {
            node.children.forEach((item) => {
              traverse(item, newNode.code);
            });
          }
        }

        treeNodes.forEach(traverse);

        return result;
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      onMounted(() => {
        getUserOrganization(globalProjectCode).then((res) => {
          orgcode.value = res.orgcode;
        });
      });

      return {
        type,
        loading,
        register,
        registerForm,
        closeModal,
        displayModuleTitle,
        onOkButtonClick,
      };
    },
  });
</script>
